﻿using ICSharpCode.SharpZipLib.Zip;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using WH.Contracts.Dtos;
using WH.Contracts.Files;
using WH.Repositories.CodeFirst;
using Rw.Core.Common;
using Rw.Core.Document;
using WH.Common.Cache;
using WH.Common.Constant;
using WH.Common.SwaggerDoc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Rw.Core.Common.Helper;

namespace WH.WebApi.Controllers.Systems
{
    /// <summary>
    /// 公共接口
    /// </summary>
    [Authorize, Route("files")]
    public class FilesController : BaseController
    {
        private readonly ICaching _caching;
        //private readonly IMapService mapService;
        private readonly IHostEnvironment _hostingEnvironment;

        private readonly CodeFirstExtension _codeFirstExtension;

        /// <summary>
        /// 公共数据接口
        /// </summary>
        /// <param name="caching"></param>
        /// <param name="hostingEnvironment"></param>
        /// <param name="codeFirstExtension"></param>
        public FilesController(ICaching caching, IHostEnvironment hostingEnvironment, CodeFirstExtension codeFirstExtension)
        {
            _caching = caching;
            _hostingEnvironment = hostingEnvironment;
            _codeFirstExtension = codeFirstExtension;
            //this.mapService = mapService;
        }

        /// <summary>
        /// 获取图形验证码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous, HttpGet("captcha")]
        public async Task<ResultResponse<CaptchaOutputDto>> GetCaptchaCodeAsync()
        {
            var imgByte = VerifyCodeHelper.GetCaptcha(out var code);
            var guid = Guid.NewGuid().ToString();

            var key = $"{BusinessFunction.CaptchaCacheKey}:{guid}";

            _caching.Add(key, Md5.MD5Hash(code.ToLower()), 600);

            var base64 = "data:image/Gif;base64," + Convert.ToBase64String(imgByte);
            var result = new ResultResponse<CaptchaOutputDto>
            {
                IsSucceed = true,
                Data = new CaptchaOutputDto
                {
                    Identity = guid,
                    ImageBase64 = base64
                }
            };

            return await Task.FromResult(result);
        }

        /// <summary>
        /// 图片上传接口
        /// </summary>
        /// <returns></returns>
        [HttpPost("upload/image")]
        [DisableRequestSizeLimit]
        public async Task<ResultResponse<string>> UploadImgageAsync(IFormFile file)
        {
            var result = new ResultResponse<string> { IsSucceed = true };
            try
            {
                if (file == null || file.Length == 0)
                {
                    result.Msg = "请选择要上传的图片";
                    return result;
                }

                var fileExt = Path.GetExtension(file.FileName);
                if (string.IsNullOrWhiteSpace(fileExt))
                {
                    result.Msg = "请确保上传的图片格式正确";
                    return result;
                }

                var images = new List<string> { "bmp", ".jpg", ".png", ".tif", ".gif", ".pcx", ".tga", ".exif", ".fpx", ".svg", ".psd", ".cdr", ".pcd", ".dxf", ".ufo", ".eps", ".ai", ".raw", ".WMF", ".webp", ".avif", ".apng" };
                if (!images.Contains(fileExt.ToLower()))
                {
                    result.Msg = "请确保上传的图片格式正确";
                    return result;
                }

                var dirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets", "upload", "images", LoginUserId ?? string.Empty);

                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                var picName = DateTime.Now.ToString("yyyyMMdd") + "-" + Guid.NewGuid() + fileExt;
                var savePath = Path.Combine(dirPath, picName);

                using (var fileStream = System.IO.File.Create(savePath))
                {
                    file.CopyTo(fileStream);
                    fileStream.Flush();
                }

                var src = Path.Combine("src", "upload", "images", $"{LoginUserId}", $"{picName}");// $"//{LoginUserId}/{picName}";

                result.IsSucceed = true;
                result.Msg = "上传成功";
                result.Data = src;
            }
            catch (Exception ex)
            {
                result.IsSucceed = false;
                result.Msg = ex.Message;
            }

            return await Task.FromResult(result);
        }

        /// <summary>
        /// 初始化种子数据
        /// </summary>
        /// <returns></returns>
        [HttpPost("initDbTablesSeedData")]
        public async Task<ResultResponse> InitDbTablesSeedData()
        {
            await _codeFirstExtension.GenerateSeedData();

            return Success();
        }


        /// <summary>
        /// API文档导出
        /// </summary>
        /// <param name="docName"></param>
        /// <returns></returns>
        [HttpGet("/doc")]
        public async Task<IActionResult> Doc([FromServices] ISwaggerDocGenerator swaggerDocGenerator, [FromServices] IWebHostEnvironment environment, string swaggerVersion = "v1")
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            var stream = await swaggerDocGenerator.GetSwaggerDocStreamAsync(swaggerVersion);
            stopwatch.Stop();
            var log = "Swagger文档导出成功，耗时" + stopwatch.ElapsedMilliseconds + "ms";
            Debug.WriteLine(log);
            var mime = "application/octet-stream";
            const string name = "SwaggerDoc.md";
            return File(stream.ToArray(), mime, name);
        }

    }
}